import axios from 'axios';
import AxiosCanceler from './axios-canceller';

const axiosCanceler = new AxiosCanceler();

axios.interceptors.request.use(config => {
  config.cancel && axiosCanceler.addPending(config)
  return config
}, error => {
  console.log('error', error);
})
axios.interceptors.response.use((response) => {
  response && axiosCanceler.removePending(response.config);
  return response.data
}, error => {
  if (axios.isCancel(error)) {
    return Promise.reject('取消请求: ' + error.config.url)
  } else {
    return Promise.reject(error)
  }
})

export function fetchData(type = 'hitokoto', signal) {
  return axios.get(`https://api.uixsj.cn/hitokoto/get?type=${type}&code=json`, { signal })
}